package com.changgou.bigdata.servicer.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.bigdata.servicer.ARecommendService;
import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.pojo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ARecommendServiceImpl implements ARecommendService {

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addWeighing(String skuId) {
        Result<Map> list = cartFeign.list();
        Map data = list.getData();
        List<CartItem> beforSkuId = (List<CartItem>) data.get("cart");
        //获取redis操作类
        BoundZSetOperations boundZSetOperations = redisTemplate.boundZSetOps(skuId);
        //遍历
        beforSkuId.forEach(beforCart->{
            String beforId = beforCart.getSkuId();
            boundZSetOperations.incrementScore(beforId,1);
            BoundZSetOperations oldCart = redisTemplate.boundZSetOps(beforId);
            oldCart.incrementScore(skuId,1);
        });
    }

    @Override
    public List<String> getPuchList(List<String> cartSkuids) {
        HashMap<String, Double> map = new HashMap<>();

        Comparator<Map.Entry<String,Double>> newNodeComparator = new Comparator<Map.Entry<String,Double>>() {
            @Override
            public int compare(Map.Entry<String,Double> o1, Map.Entry<String,Double> o2) {
                double v = o1.getValue() - o2.getValue();
                return -(int) v;
            }
        };
        String s = cartSkuids.toString();
        redisTemplate.opsForZSet().unionAndStore("",cartSkuids,s);
        Set<ZSetOperations.TypedTuple<String>> likes =  redisTemplate.boundZSetOps(s).reverseRangeWithScores(0,19);
        List<String> list = likes.stream().map(ZSetOperations.TypedTuple::getValue).collect(Collectors.toList());
        return list;
    }
}
